<template>
  <div class="LoginComponent">
    <NavBar title="" titleColor="#ccc">
      <template #left>
        <div class="nav-bar-left-icon" @click="closeLoginModal">
          <Icon name="close" color="#ccc" size="18"></Icon>
        </div>
      </template>
      <template #right>
        <span @click="showRegister = true">注册账号</span>
      </template>
    </NavBar>

    <!-- 登录表单 -->
    <div class="login-form">
      <h2>登陆后即可展示自己</h2>
      <div class="login-form-item">
        <input type="text" placeholder="请输入邮箱" v-model="emailRef" />
      </div>
      <div class="login-form-item">
        <input type="password" placeholder="请输入密码" v-model="passwordRef" />
      </div>
      <!-- 忘记密码 -->
      <div class="login-form-item" @click="goRetrievePasswordView">
        <span>忘记密码？</span>
      </div>
      <div class="login-form-item">
        <button @click="handleLogin">登录</button>
      </div>
    </div>

    <!-- 注册组件（带过渡） -->
    <transition name="fade">
      <registerComponent v-if="showRegister" v-model="showRegister" />
    </transition>

    <!-- 找回密码组件（带过渡） -->
    <transition name="fade">
      <forgetPasswordComponent v-if="showForgetPassword" v-model="showForgetPassword" :email="emailRef" />
    </transition>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import { defineAsyncComponent } from 'vue'
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import { userLginAPI, userRetrievePasswordAPI } from '@/api/Auth'
import { useUserStore } from '@/stores/userStatus'
import { useUserIDStore } from '@/stores/UserID'
import { showToast } from '@/utils/showToast'

// 注入全局 socket 实例
const socket = inject('socket')

// 状态管理
const userStore = useUserStore()
const userIDStore = useUserIDStore()

// 表单数据
const emailRef = ref('583514368@qq.com')
const passwordRef = ref('123456')

// 控制子组件显示状态
const showRegister = ref(false)
const showForgetPassword = ref(false)

// 异步加载子组件
const registerComponent = defineAsyncComponent(() =>
  import('@/views/home/RegisterComponents/index.vue')
)
const forgetPasswordComponent = defineAsyncComponent(() =>
  import('@/views/home/RetrievePassword/index.vue')
)

/**
 * 登录处理逻辑
 */
const handleLogin = async () => {
  const data = {
    email: emailRef.value,
    password: passwordRef.value,
  }

  const res = await userLginAPI(data)

  if (res.code === 200) {
    // 更新用户登录状态
    userStore.updateLoginStatus(true)
    // 存储用户信息（含 userId）
    userIDStore.setUserInfo(res.data)

    // 通过 WebSocket 告知后端当前用户已登录
    const userId = res.data.userId
    if (userId && socket) {
      socket.emit('login', userId)
    }



    // 关闭登录弹窗
    closeLoginModal()
    // 显示成功提示
    showToast('登录成功', {
      position: 'bottom'
    })
  } else {
    alert(res.msg || '登录失败')
  }
}

/**
 * 关闭登录弹窗
 */
const closeLoginModal = () => {
  userStore.closeLoginModal()
}

/**
 * 跳转至找回密码流程
 * 先验证邮箱是否存在
 */
const goRetrievePasswordView = async () => {
  const res = await userRetrievePasswordAPI(emailRef.value)
  if (res.code === 200) {
    showForgetPassword.value = true // 显示找回密码组件
  } else {
    console.log('邮箱不存在:', res)
    // 可替换为 ElMessage.error('邮箱不存在') 等 UI 提示
  }
}
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.LoginComponent {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  z-index: 1000;
  padding: 20px;

  .login-form {
    min-width: 300px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 20px;
    border-radius: 10px;

    h2 {
      font-size: 20px;
      color: #000;
    }

    .login-form-item {
      display: flex;
      flex-direction: column;
      gap: 5px;

      input {
        padding: 10px;
        border-radius: 5px;
        background-color: #f9f9f9;
      }

      button {
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        background-color: #007bff;
        color: #fff;
        cursor: pointer;
      }

      span {
        font-size: 14px;
        color: #ccc;
        cursor: pointer;
      }
    }
  }
}

// 过渡效果：从右滑入/滑出
.fade-enter-active,
.fade-leave-active {
  transition: all 0.6s ease;
}

.fade-enter-from,
.fade-leave-to {
  transform: translateX(100%);
}
</style>